struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
// 思路: 递归方法, 每个节点交换左右子节点
class Solution
{
public:
    TreeNode *invertTree(TreeNode *root)
    {
        if (!root)
            return root;
        TreeNode *temp = root->left; // 交换左右子节点
        root->left = root->right;
        root->right = temp;
        invertTree(root->left); // 交换完成之后递归交换左右子节点
        invertTree(root->right);
        return root;
    }
};